package com.dtjd.playcoinmonkey.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.res.ResourcesCompat;

import com.dtjd.playcoinmonkey.DialogClick;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.databinding.Dialog2Binding;
import com.dtjd.playcoinmonkey.databinding.DialogBinding;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.text.DecimalFormat;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;

public class Tools {
    public static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCug4o2zlSIvdxE8pjqda9Rn/HUb6LeTRYNl6zJh7AHc4X6eKRsSshQ5iBKLMDV6txhVxKJKIRvabIxH5UpIo458xW4P1JdudDKzC3Ormpx17uM1DiZ+d67xg5ly+j0fzayaqXnLMSISD8JHYXmIb4EbjnsTLWcoV/80d7/FL3XbQIDAQAB";
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String encrypt(String content)  {
        try {
            PublicKey publicKey = null;
            publicKey = getPublicKey(publicKeyStr);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] cipherText = cipher.doFinal(content.getBytes());
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            return "";
        }
    }
    public static boolean isEmail(String email){
        if (null==email || "".equals(email)) return false;
        Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        Matcher m = p.matcher(email);
        return m.matches();
    }
    public static boolean passwordCorrect(String password){
        if (password.length()<8 || password.length()>20)return  false;
        Matcher m = Pattern.compile(".*[a-zA-Z].*").matcher(password);
        if (!m.find()){
            return false;
        }
        Matcher m1 = Pattern.compile(".*[0-9].*").matcher(password);
        return m1.matches();
    }
    public static int px2dip(Context context, float pxValue) {
        return (int) (pxValue / context.getResources().getDisplayMetrics().density + 0.5f);
    }
    public static int dip2px(Context context,float dpValue) {
        return (int) (dpValue * context.getResources().getDisplayMetrics().density + 0.5f);
    }
    public static void  showDialog(Activity activity, String title, String content, String leftText, DialogClick leftDialogClick, String rightText, DialogClick rightDialogClick){
        @NonNull DialogBinding dbinding = DialogBinding.inflate(activity.getLayoutInflater());
        dbinding.dialogTitle.setText(title);
        dbinding.dialogContent.setText(content);
        dbinding.dialogButtonLeft.setText(leftText);
        dbinding.dialogButtonRight.setText(rightText);
        AlertDialog dialog=new AlertDialog.Builder(activity).setView(dbinding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width = ((int)(activity.getWindowManager().getDefaultDisplay().getWidth() * 0.8));
        dialog.getWindow().setAttributes(p);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(),R.drawable.dialogbg,null));
        dbinding.dialogButtonLeft.setOnClickListener(view -> leftDialogClick.click(view,dialog));
        dbinding.dialogButtonRight.setOnClickListener(view -> rightDialogClick.click(view,dialog));
    }
    public static void  showDialog2(Activity activity, String title, String content, String leftText,String tips, DialogClick click ){
        @NonNull Dialog2Binding dbinding = Dialog2Binding.inflate(activity.getLayoutInflater());
        dbinding.dialog2Title.setText(title);
        dbinding.dialog2Content.setText(content);
        dbinding.dialog2Button.setText(leftText);
        dbinding.dialog2Ps.setText(tips);
        AlertDialog dialog=new AlertDialog.Builder(activity).setView(dbinding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width = ((int)(activity.getWindowManager().getDefaultDisplay().getWidth() * 0.8));
        dialog.getWindow().setAttributes(p);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(),R.drawable.dialogbg,null));
        dbinding.dialog2Button.setOnClickListener(view -> click.click(view,dialog));
    }
    public static boolean hasExternalStoragePermission(Context context){
        return context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED;
    }
    public static void toast(String s) {
        Toast.makeText(MyApplication.instance, s, Toast.LENGTH_SHORT).show();
    }
    public static boolean copyFile(String from, String to) {
        try {
            FileInputStream fileInputStream = new FileInputStream(from);
            FileOutputStream fileOutputStream = new FileOutputStream(to);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
           return false;
        }
    }
    public static String getPercent(int x, int y) {
        double d1 = x * 1.0;
        double d2 = y * 1.0;
        DecimalFormat decimalFormat = new DecimalFormat("##.0%");
        return decimalFormat.format(d1 / d2);
    }
}